<template>
  <div class="login">
    <n-form
      class="login_form"
      :model="loginModel"
    >
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="loginModel.username" clearable placeholder="请输入用户名" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input v-model:value="loginModel.password" type="password" show-password-on="mousedown"  placeholder="请输入密码" />
      </n-form-item>
      <div class="login_btn">
        <n-button @click="handleLogin" strong secondary  type="primary">
          登录
        </n-button>
        <n-button @click="showRegisterModal = true">
          注册
        </n-button>
      </div>
    </n-form>

    <!-- 注册对话框 -->
    <n-modal v-model:show="showRegisterModal" preset="dialog" title="用户注册">
      <n-form
        :model="registerModel"
        :rules="rules"
        ref="registerFormRef"
      >
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="registerModel.username" placeholder="请输入用户名" />
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input v-model:value="registerModel.password" type="password" placeholder="请输入密码" />
        </n-form-item>
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input v-model:value="registerModel.confirmPassword" type="password" placeholder="请确认密码" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showRegisterModal = false">取消</n-button>
        <n-button type="primary" strong secondary  @click="handleRegister">确认注册</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref,onMounted } from 'vue';
import { NForm, NFormItem, NInput, NButton, NModal, useMessage } from 'naive-ui'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { request } from '@/utils/request';
const store = useStore();
const router = useRouter();
const message = useMessage();
const registerFormRef = ref(null);
const showRegisterModal = ref(false);

const loginModel = ref({    
  username: '',
  password: ''
});

const registerModel = ref({
  username: '',
  password: '',
  confirmPassword: ''
});

const rules = {
  username: {
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  },
  confirmPassword: {
    required: true,
    message: '请确认密码',
    trigger: 'blur',
    validator: (rule, value) => {
      return value === registerModel.value.password || new Error('两次输入的密码不一致')
    }
  }
};

const handleLogin = async () => {
  if (!loginModel.value.username || !loginModel.value.password) {
    message.error('请输入用户名和密码');
    return;
  }else{
    await request({
      url:'/login/',
      method:'post',
      data:loginModel.value
    })
    .then(res=>{
      if(res.code === 200){
        message.success('登录成功！');
        router.push("/user");
        store.commit('setUserInfo',res.data);
        store.commit('setLoginInfo',loginModel.value);
      }else{
        message.error(res.message);
      }
    })
  }
  console.log('登录信息：', loginModel.value);
};

const handleRegister = async () => {
  try {
    await registerFormRef.value?.validate()
    await request({
      url:"/register/",
      method:"POST",
      data:registerModel.value
    })
    .then(res=>{
      if(res.code === 200){
        message.success('注册成功！');
        showRegisterModal.value = false
        // 可选：自动填充登录表单
        loginModel.value = {
          username: registerModel.value.username,
          password: registerModel.value.password
        }
        // 清空表单
        registerModel.value = {
          username: '',
          password: '',
          confirmPassword: ''
        }
      }else{
        message.error(res.message);
      }
    })
  } catch (errors) {
    if (Array.isArray(errors)) {
      // 表单验证错误
      const firstError = errors[0]?.[0]
      if (firstError) {
        message.error(firstError.message)
      }
    } else {
      // API调用错误
      message.error('注册失败，请稍后重试')
    }
  }
}
onMounted(()=>{
  if(store.state.userInfo){
    router.push("/user");
  }
})
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px);
  .login_form {
    width: 300px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    .login_btn{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>

